<template>
  <view class="container">
    <!-- 顶部选项卡 -->
    <view class="tabs">
      <view
          :class="['tab-item', activeTab === 'list' ? 'active' : '']"
          @click="switchTab('list')"
      >
        列表
      </view>
      <view
          :class="['tab-item', activeTab === 'recommend' ? 'active' : '']"
          @click="switchTab('recommend')"
      >
        推荐
      </view>
    </view>

    <!-- 搜索栏 -->
    <view class="search-bar">
      <input
          class="search-input"
          placeholder="搜索商品"
          placeholder-class="placeholder"
          v-model="searchKeyword"
          @confirm="searchProducts"
      />
      <uni-icons class="search-icon" type="search" size="22" color="#999"></uni-icons>
    </view>

    <!-- 排序选项 -->
    <view class="sort-options">
      <view
          class="sort-item"
          v-for="(item, index) in sortOptions"
          :key="index"
          :class="{'active': sortType === item.value}"
          @click="sortProducts(item.value)"
      >
        {{ item.label }}
        <uni-icons
            v-if="item.sortable"
            :type="sortDirection === 'asc' ? 'arrowdown' : 'arrowup'"
            size="12"
            color="#e54d42"
        />
      </view>
    </view>

    <!-- 商品列表 -->
    <scroll-view class="goods-list" scroll-y>
      <view
          v-for="(goods, index) in filteredGoodsList"
          :key="goods.id"
          class="goods-item"
      >
        <image
            :src="goods.thumb"
            class="goods-image"
            mode="aspectFill"
            @click="goGoodsDetail(goods.id)"
        />

        <!-- 排名标签 -->
        <view v-if="goods.ranking" class="ranking-tag">

          <view class="tag-tail"></view>
          <view class="tag-content">
            本店{{ goods.rankingType }}第{{ goods.ranking }}
          </view>
        </view>

        <view class="goods-info">
          <view class="goods-title">
            <view class="brand">{{ goods.brand }}</view>
            {{ goods.name }}
          </view>
          <view class="goods-desc">{{ goods.description }}</view>

          <!-- 促销信息 -->
          <view v-if="goods.promotion" class="promotion">
            <text class="promo-tag">爆款推荐</text>
            <text class="original-price">普通价：￥{{ goods.originalPrice }}</text>
            <text class="discount-price">会员价：￥{{ goods.price }}</text>
          </view>

          <view class="price-row">
            <view class="price-section">
              <text class="price">￥{{ goods.skus[0]?.price }}</text>
              <text class="sold">{{ goods.sold }}件已售</text>
            </view>

            <view class="cart-btn" @click.stop="showSkuPopup(goods)" v-if="hasStock(goods)">
              <text class="custom-plus">+</text>
            </view>
            <view class="sold-out" v-else>
              <text>已售罄</text>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 规格选择弹窗 -->
    <view class="popup-mask" v-if="showPopup" @click="hidePopup">
      <view class="sku-popup" @click.stop>
        <view class="popup-header">
          <image :src="selectedGoods.thumb" class="popup-image"/>
          <view class="popup-info">
            <view class="popup-price">
              ¥{{ selectedGoods.price }}
            </view>
            <view class="popup-stock">
              库存: {{ selectedGoods.stock }}件
            </view>
            <view class="popup-sku">
              已选：
              <text v-if="selectedGoods.specifications" class="highlight">{{ selectedGoods.specifications }}</text>
              <text v-else class="highlight">请选择规格</text>
            </view>
          </view>
          <view class="close-btn" @click="hidePopup">
            <uni-icons type="close" size="22" color="#999"/>
          </view>
        </view>

        <view class="sku-section">
          <text class="sku-title">型号</text>
          <!-- 弹窗内规格选项 -->
          <view class="sku-options">
            <view
                v-for="(sku, index) in selectedGoods.skus"
                :key="index"
                :class="['sku-option', activeSpec === index ? 'active' : '']"
                @click="selectSpec(index)"
            >
              {{ sku.spec }}
            </view>
          </view>

          <!-- 弹窗价格展示 -->
          <view class="popup-price">
            ¥{{ selectedGoods.price }}
          </view>

          <!-- 弹窗库存展示 -->
          <view class="popup-stock">
            库存: {{ selectedGoods.stock }}件
          </view>

        </view>

        <view class="qty-section">
          <text class="sku-title">数量</text>
          <view class="qty-control">
            <view class="qty-btn" @click="adjustQuantity(-1)">
              <text class="custom-low">-</text>
            </view>
            <input class="qty-input" v-model="quantity" type="number"/>
            <view class="qty-btn" @click="adjustQuantity(1)">
              <text class="custom-plus">+</text>
            </view>
          </view>
        </view>

        <view class="popup-footer">
          <button class="add-to-cart" @click="addToCart">
            <uni-icons type="cart" size="20" color="#fff" style="margin-right: 6px;"/>
            加入购物车
          </button>
          <button class="buy-now" @click="buyNow">
            立即购买
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import {ref, reactive, computed} from 'vue'

// 当前激活的选项卡
const activeTab = ref('list')
// 搜索关键词
const searchKeyword = ref('')
// 排序类型
const sortType = ref('default')
// 排序方向
const sortDirection = ref('asc')
// 弹窗显示状态
const showPopup = ref(false)
// 选中的规格
const activeSpec = ref(0)
// 购买数量
const quantity = ref(1)

// 排序选项
const sortOptions = reactive([
  {label: '综合', value: 'default', sortable: false},
  {label: '销量', value: 'sales', sortable: true},
  {label: '价格', value: 'price', sortable: true},
  {label: '上新', value: 'new', sortable: false}
])

// 商品规格选项
const specifications = reactive([
  "经典-速干王(1大瓶)",
  "经典-速干王(1大瓶+1小瓶)",
  "经典-速干王(1大瓶+2小瓶)",
  "经典-速干王(2大瓶)"
])

// 当前选中的商品
const selectedGoods = ref(null)

// 商品数据
const goodsList = ref([
  {
    id: 1,
    brand: "迪漾|DIANA",
    name: "永恒系列极软0.05法式睫毛",
    description: "0.05圆毛/多根/开花，可用于各种技术全能款",
    thumb: "https://s1.aigei.com/prevfiles/fe0c75404d6b4776aa95df8f2fa876d7.png?e=2051020800&token=P7S2Xpzfz11vAkASLTkfHN7Fw-oOZBecqeJaxypL:c8p1DpbBA8zmuDJPShjFAbE6gQk=",
    sold: 2000,
    ranking: 1,
    rankingType: "人气榜",
    stock: 20,
    promotion: true,
    specifications: "",
    skus: [
      { spec: "经典-速干王(1大瓶)", price: 48, originalPrice: 33, stock: 20 },
      { spec: "经典-速干王(1大瓶+1小瓶)", price: 58, originalPrice: 40, stock: 15 },
      { spec: "经典-速干王(1大瓶+2小瓶)", price: 68, originalPrice: 50, stock: 10 },
      { spec: "经典-速干王(2大瓶)", price: 88, originalPrice: 70, stock: 5 }
    ],
    price: 48,
    originalPrice: 33
  },
  {
    id: 2,
    brand: "迪漾|DIANA",
    name: "永恒系列极软0.05法式睫毛",
    description: "轻量装48元/盒起 可用于可种技...",
    thumb: "https://s1.aigei.com/prevfiles/fe0c75404d6b4776aa95df8f2fa876d7.png?e=2051020800&token=P7S2Xpzfz11vAkASLTkfHN7Fw-oOZBecqeJaxypL:c8p1DpbBA8zmuDJPShjFAbE6gQk=",
    sold: 2424,
    ranking: 3,
    rankingType: "销量榜",
    stock: 44,
    specifications: "",
    skus: [
      { spec: "经典-速干王(1大瓶)", price: 45, originalPrice: 33, stock: 44 },
      { spec: "经典-速干王(1大瓶+1小瓶)", price: 55, originalPrice: 40, stock: 30 },
      { spec: "经典-速干王(1大瓶+2小瓶)", price: 65, originalPrice: 50, stock: 20 },
      { spec: "经典-速干王(2大瓶)", price: 85, originalPrice: 70, stock: 10 }
    ],
    price: 48,
    originalPrice: 33
  },
  {
    id: 3,
    brand: "美睫师专用",
    name: "超强持久睫毛胶水",
    description: "无刺激 超强持久 不易泛白",
    thumb: "https://s1.aigei.com/prevfiles/fe0c75404d6b4776aa95df8f2fa876d7.png?e=2051020800&token=P7S2Xpzfz11vAkASLTkfHN7Fw-oOZBecqeJaxypL:c8p1DpbBA8zmuDJPShjFAbE6gQk=",
    sold: 1523,
    ranking: 5,
    rankingType: "热销榜",
    stock: 12,
    promotion: true,
    specifications: "",
    skus: [
      { spec: "标准装", price: 125, originalPrice: 150, stock: 12 },
      { spec: "加量装", price: 150, originalPrice: 180, stock: 8 }
    ],
    price: 48,
    originalPrice: 33
  },
  {
    id: 4,
    brand: "日本进口",
    name: "精密镊子套装",
    description: "专业美睫工具 防磁耐用",
    thumb: "https://s1.aigei.com/prevfiles/fe0c75404d6b4776aa95df8f2fa876d7.png?e=2051020800&token=P7S2Xpzfz11vAkASLTkfHN7Fw-oOZBecqeJaxypL:c8p1DpbBA8zmuDJPShjFAbE6gQk=",
    sold: 987,
    stock: 0,
    specifications: "",
    skus: [
      { spec: "单支装", price: 280, originalPrice: 320, stock: 0 },
      { spec: "双支套装", price: 520, originalPrice: 600, stock: 0 }
    ],
    price: 48, // 手动添加这个字段
    originalPrice: 33
  }
])


// 过滤后的商品列表
const filteredGoodsList = computed(() => {
  // 根据搜索关键词过滤
  let filtered = goodsList.value
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(item =>
        item.name.toLowerCase().includes(keyword) ||
        item.brand.toLowerCase().includes(keyword) ||
        item.description.toLowerCase().includes(keyword)
    )
  }

  // 根据标签过滤
  if (activeTab.value === 'recommend') {
    filtered = filtered.filter(item => item.promotion)
  }

  // 根据排序类型排序
  if (sortType.value === 'sales') {
    filtered = [...filtered].sort((a, b) =>
        sortDirection.value === 'asc' ? a.sold - b.sold : b.sold - a.sold
    )
  } else if (sortType.value === 'price') {
    filtered = [...filtered].sort((a, b) =>
        sortDirection.value === 'asc' ? a.price - b.price : b.price - a.price
    )
  } else if (sortType.value === 'new') {
    // 简单的按ID倒序模拟新品
    filtered = [...filtered].sort((a, b) => b.id - a.id)
  }

  return filtered
})

// 切换选项卡
const switchTab = (tab) => {
  activeTab.value = tab
}

// 排序商品
const sortProducts = (type) => {
  if (sortType.value === type && ['price', 'sales'].includes(type)) {
    // 切换排序方向
    sortDirection.value = sortDirection.value === 'asc' ? 'desc' : 'asc'
  } else {
    // 设置新的排序类型
    sortType.value = type
    sortDirection.value = 'asc'
  }
}

// 搜索商品
const searchProducts = () => {
  // 实际项目中可能发送搜索请求
  console.log('搜索关键词:', searchKeyword.value)
}

// 显示规格弹窗
const showSkuPopup = (goods) => {
  selectedGoods.value = {
    ...goods,
    price: goods.skus[0]?.price || 0, // 默认第一个SKU的价格
    originalPrice: goods.skus[0]?.originalPrice || 0, // 原价
    stock: goods.skus[0]?.stock || 0, // 库存
    specifications: goods.skus[0]?.spec || '请选择规格', // 规格名称
  }
  activeSpec.value = 0
  quantity.value = 1
  showPopup.value = true
}



// 隐藏弹窗
const hidePopup = () => {
  showPopup.value = false
}

// 选择规格
const selectSpec = (index) => {
  activeSpec.value = index
  const selectedSku = selectedGoods.value.skus[index]
  selectedGoods.value.price = selectedSku.price
  selectedGoods.value.originalPrice = selectedSku.originalPrice
  selectedGoods.value.stock = selectedSku.stock
  selectedGoods.value.specifications = selectedSku.spec
}


// 调整数量
const adjustQuantity = (delta) => {
  let newQty = quantity.value + delta
  if (newQty < 1) newQty = 1
  if (newQty > selectedGoods.value.stock) newQty = selectedGoods.value.stock
  quantity.value = newQty
}

// 添加到购物车
const addToCart = () => {
  if (!selectedGoods.value.specifications) {
    // 请选择规格逻辑
    return
  }

  uni.showToast({
    title: `已添加 ${quantity.value} 件商品到购物车`,
    icon: 'success'
  })
  hidePopup()
}

// 立即购买
const buyNow = () => {
  if (!selectedGoods.value.specifications) {
    // 请选择规格逻辑
    return
  }

  uni.navigateTo({
    url: `/pages/order/confirm?id=${selectedGoods.value.id}&qty=${quantity.value}`
  })
  hidePopup()
}

// 检测商品是否有库存
const hasStock = (goods) => goods.stock > 0

// 跳转到商品详情页
const goGoodsDetail = (id) => {
  uni.navigateTo({
    url: `/pages/goods/detail?id=${id}`
  })
}
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 20rpx;
}

.tabs {
  display: flex;
  height: 90rpx;
  background-color: #fff;
  position: sticky;
  top: 0;
  z-index: 10;
  border-bottom: 1rpx solid #eee;
}

.tab-item {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 32rpx;
  color: #666;
  position: relative;
  font-weight: 500;
}

.tab-item.active {
  color: #e54d42;
  font-weight: bold;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60rpx;
  height: 6rpx;
  background-color: #e54d42;
  border-radius: 3rpx;
}

.search-bar {
  position: relative;
  margin: 20rpx;
  background-color: #fff;
  border-radius: 60rpx;
  height: 70rpx;
  padding: 0 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.search-input {
  height: 100%;
  padding-left: 60rpx;
  font-size: 28rpx;
  color: #333;
}

.search-icon {
  position: absolute;
  left: 30rpx;
  top: 24rpx;
}

.placeholder {
  color: #ccc;
  font-size: 28rpx;
}

.sort-options {
  display: flex;
  background-color: #fff;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #eee;
  margin: 0 20rpx;
}

.sort-item {
  flex: 1;
  text-align: center;
  font-size: 28rpx;
  color: #666;
  display: flex;
  align-items: center;
  justify-content: center;
}

.sort-item.active {
  color: #e54d42;
  font-weight: bold;
}

.goods-list {
  flex: 1;
  padding: 20rpx;
}

.goods-item {
  display: flex;
  background-color: #fff;
  border-radius: 20rpx;
  margin-bottom: 20rpx;
  padding: 20rpx;
  position: relative;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.03);
}

.goods-image {
  width: 240rpx;
  height: 240rpx;
  border-radius: 10rpx;
  background-color: #f8f8f8;
}

.ranking-tag {
  position: absolute;
  top: 30rpx;
  left: 250rpx;
  z-index: 2;
}

.tag-content {
  background-color: #ff5555;
  color: #fff;
  font-size: 22rpx;
  padding: 4rpx 16rpx;
  border-top-left-radius: 6rpx;
  border-bottom-left-radius: 6rpx;
}

.tag-tail {
  position: absolute;
  top: 0;
  right: -20rpx;
  width: 20rpx;
  height: 26rpx;
  background-color: #d44a44;
  clip-path: polygon(0 0, 0 100%, 100% 50%);
}

.goods-info {
  flex: 1;
  padding-left: 20rpx;
  display: flex;
  flex-direction: column;
}

.goods-title {
  font-size: 30rpx;
  color: #333;
  margin-bottom: 10rpx;
  line-height: 1.4;
  font-weight: 500;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.brand {
  color: #e54d42;
  display: inline-block;
  margin-right: 10rpx;
  font-weight: bold;
}

.goods-desc {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 15rpx;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.promotion {
  background-color: #fff5f5;
  padding: 8rpx 12rpx;
  border-radius: 6rpx;
  margin-bottom: 15rpx;
}

.promo-tag {
  background-color: #ffe1e1;
  color: #e54d42;
  font-size: 22rpx;
  padding: 2rpx 8rpx;
  border-radius: 4rpx;
  margin-right: 10rpx;
}

.original-price {
  font-size: 24rpx;
  color: #999;
  text-decoration: line-through;
  margin-right: 10rpx;
}

.discount-price {
  color: #e54d42;
  font-size: 24rpx;
  font-weight: bold;
}

.price-row {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  margin-top: auto;
}

.price-section {
  display: flex;
  align-items: flex-end;
}

.price {
  color: #e54d42;
  font-size: 36rpx;
  font-weight: bold;
  margin-right: 10rpx;
}

.sold {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 3rpx;
}

.cart-btn {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  background-color: #fff0f0;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1rpx solid #ffe1e1;

  /* 整体左移 */
  transform: translateX(-15px);
}

.sold-out {
  background-color: #f5f5f5;
  padding: 6rpx 14rpx;
  border-radius: 30rpx;
  font-size: 24rpx;
  color: #999;
}

.popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: flex-end;
  z-index: 999;
}

.sku-popup {
  background-color: #fff;
  border-top-left-radius: 24rpx;
  border-top-right-radius: 24rpx;
  padding: 30rpx;
  width: 100%;
  max-height: 80vh;
  overflow-y: auto;
}

.popup-header {
  display: flex;
  padding-bottom: 30rpx;
  border-bottom: 1rpx solid #eee;
  position: relative;
}

.popup-image {
  width: 180rpx;
  height: 180rpx;
  border-radius: 10rpx;
  margin-right: 20rpx;
}

.popup-info {
  flex: 1;
}

.popup-price {
  color: #e54d42;
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.popup-stock {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 10rpx;
}

.popup-sku {
  font-size: 24rpx;
  color: #333;
}

.highlight {
  color: #e54d42;
  font-weight: 500;
}

.close-btn {
  position: absolute;
  top: 10rpx;
  right: 10rpx;
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  background-color: #f5f5f5;
  display: flex;
  justify-content: center;
  align-items: center;
}

.sku-section {
  margin-top: 30rpx;
}

.sku-title {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
  margin-bottom: 20rpx;
  display: block;
}

.sku-options {
  display: flex;
  flex-wrap: wrap;
  margin-top: 10rpx;
}

.sku-option {
  padding: 16rpx 30rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  margin-right: 20rpx;
  margin-bottom: 20rpx;
  font-size: 26rpx;
  color: #333;
  border: 1rpx solid transparent;
}

.sku-option.active {
  background-color: #fff0f0;
  color: #e54d42;
  border: 1rpx solid #e54d42;
}

.qty-section {
  margin-top: 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.qty-control {
  display: flex;
  align-items: center;
}

.qty-btn {
  width: 50rpx;
  height: 50rpx;
  border-radius: 50%;
  background-color: #f5f5f5;
  display: flex;
  justify-content: center;
  align-items: center;
}

.qty-input {
  width: 80rpx;
  height: 50rpx;
  text-align: center;
  font-size: 28rpx;
  margin: 0 10rpx;
  border: 1rpx solid #eee;
  border-radius: 8rpx;
}

.popup-footer {
  display: flex;
  margin-top: 40rpx;
  border-top: 1rpx solid #eee;
  padding-top: 30rpx;
}

button {
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 40rpx;
  font-size: 30rpx;
  padding: 0;
  margin: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

button::after {
  border: none;
}

.add-to-cart {
  background: linear-gradient(to right, #ffd01e, #ff9600);
  color: #333;
  flex: 1.4;
  margin-right: 20rpx;
}

.buy-now {
  background: linear-gradient(to right, #ff6034, #ff1a0d);
  color: #fff;
  flex: 1;
}

.custom-plus {
  font-size: 28px;
  color: #e54d42;
  display: block;

}

.custom-low {
  font-size: 28px;
  color: #214b80;
  display: block;
}
</style>